package xin.sparrow.log.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xin.sparrow.log.annotation.WebLog;
import xin.sparrow.log.request.RequestAndResponseLog;
import xin.sparrow.log.request.RequestThreadLocal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * Created by wancheng on 2019/10/11.
 * controller层日志注解拦截器
 */
@Slf4j
public class ControllerLogInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //获取当前方法上的指定注解
        WebLog webLog = method.getAnnotation(WebLog.class);
        //判断当前注解是否存在
        if(webLog != null){
            long startTime = System.currentTimeMillis();
            RequestThreadLocal.set().setDesc(webLog.name()).setTime(new Date(startTime));
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //获取当前方法上的指定注解
        WebLog webLog = method.getAnnotation(WebLog.class);
        //判断当前注解是否存在
        if(webLog != null){
            RequestAndResponseLog requestLog = RequestThreadLocal.get();
            long endTime = System.currentTimeMillis();
            long startTime = requestLog.getTime().getTime();
            requestLog.setResponseTime(endTime - startTime);
            log.info("说明:{} 访问uri:{} 参数:{} 地址:{} 返回结果:{},响应时间:{}",
                    requestLog.getDesc(),
                    requestLog.getUri(),
                    requestLog.getReqParam(),
                    requestLog.getIp(),
                    requestLog.getResponse(),
                    requestLog.getResponseTime());
        }
        RequestThreadLocal.remove();
    }
}
